import React, { Component } from 'react';
import { Calendar, Button, Grid, Table, Icon, Balloon, Dialog, Message } from '@alifd/next';
import FoundationSymbol from '@icedesign/foundation-symbol';
import IceContainer from '@icedesign/container';
import moment from 'moment';
const TableExport = require('tableexport');
import request from '../../instances/request';
import ScheduleDialog from './ScheduleDialog';

require('./index.scss');

const { Row, Col } = Grid;

moment.locale('zh-cn', {
  monthsShort : [
    "一月","二月","三月","四月",
    "五月","六月","七月","八月",
    "九月","十月","十一月","十二月",
  ],
  weekdaysShort: [
    '周一','周二','周三','周四','周五','周六','周日'
  ]
});

const currentDate = moment();
const localeData = currentDate.clone().localeData();
const monthLocale = localeData.monthsShort();

const alignArray = ['t', 'r', 'l', 'b'];

class WorkingSchedule extends Component {
  constructor(props) {
    super(props);

    this.state = {
      __loading : false,
      teamMember: [],
      scheduleList: [],
      scheduleTableData: [],
      currentDate: moment(),
      showEditTable: false,
      exportTableData: [],
    };
  }

  // todo: 为什么这里Calendar能够监听到this.state.scheduleList的变化？
  /**
   * 当月每一天反复执行
   * @param date
   * @return {*}
   */
  dateCellRender(date) {
    if(date.month() !== this.state.currentDate.month()) {
      return date.date();
    }
    let day = date.date();
    let oneDayData = this.state.scheduleList[day - 1];
    let dataList = [];
    if( oneDayData ) {
      dataList = oneDayData.map((ele, idx) => {

        let teamMembersList = this.state.teamMember.filter((user, i) => {
          return user.teamName === ele.teamName;
        }).map((user, i) => {
          return <div key={i}>{user.username}</div>
        });

        return {
          className: `event event-${ele.teamName.replace('组', '')}`,
          content: (
            <Balloon closable={false}
                     align={alignArray[idx % 4] || 'b'}
                     triggerType="hover"
                     type="normal"
                     trigger={(
                       <div style={{ textAlign: 'right' }}>
                         <span className="dot">&#8226;&nbsp;&nbsp;</span>
                         <span>{ele.scheduleType}：&nbsp;&nbsp;</span>
                         <span>{ele.teamName}</span>
                       </div>
                     )} >
              <div className="working-schedule-ballon">
                <div className='working-schedule-ballon-title'>{ele.teamName}成员</div>
                { teamMembersList }
              </div>
            </Balloon>
          )
        }
      });
    }

    return (<div className="custom-calendar-cell">
      <div className="custom-calendar-cell-value">{day}</div>
      <div className="custom-calendar-cell-content">
        <ul className="calendar-data-list">
          {dataList.map((item, key) => <li className={`${item.className}`} key={key}>{item.content}</li>)}
        </ul>
      </div>
    </div>);
  }

  monthCellRender(date) {
    if (currentDate.month() === date.month()) {
      return (<div>
        <div>{monthLocale[date.month()]}</div>
      </div>);
    }
    return monthLocale[date.month()];
  }

  onVisibleMonthChange(date) {
    let year = date.year();
    let month = date.month();
    let day = date.date();
    this
      .getScheduleList({ year: year, month: month })
      .then((scheduleList) => {
        this.setState({
          scheduleTableData: scheduleList[day - 1] || [],
          scheduleList,
          currentDate: date,
        });
      });
  }

  onCellSelect(date) {
    let day = date.date();
    let { scheduleList } = this.state;
    this.setState({
      scheduleTableData: scheduleList[day - 1] || [],
      currentDate: date,
    })
  }

  handleAddAndEdit(record, e) {
    e.preventDefault();
    ScheduleDialog.show({
      value: record,
      onOk: (newRecord) => {
        // 添加数据
        let { id, teamName, scheduleTime, startTime, endTime, scheduleType } = newRecord;
        let currentDate = this.state.currentDate;
        let year = currentDate.year();
        let month = currentDate.month();
        let day = currentDate.date();
        return this.addOrUpdateSchedule({
          id,
          teamName,
          scheduleTime,
          startTime,
          endTime,
          year,
          month,
          day,
          scheduleType,
        }).then(({newTableData, newList}) => {
          Message.success("操作成功");
          this.setState({
            scheduleTableData: newTableData,
            scheduleList: newList,
          }, () => {
            ScheduleDialog.hide();
          });
        });
      },
      onClose: () => {
        ScheduleDialog.hide();
      },
      onCancel: () => {
        ScheduleDialog.hide();
      },
    });
  }

  handleDelete(record, e) {
    e.preventDefault();
    console.log(record.id);
    let dialog = Dialog.confirm({
      title: '删除确认',
      content: '您确认删除这一条目吗？',
      onOk: () => {
        return this
          .deleteSchedule({ id: record.id })
          .then((newList) => {
            let newTableData = this.state.scheduleTableData
              .filter((ele, idx) => {
                return ele.id !== record.id;
              });
            this.setState({
              scheduleList: newList,
              scheduleTableData: newTableData,
            });
            dialog.hide();
            Message.success("删除成功");
          });
      },
      onCancel: () => {
        dialog.hide();
      },
      onClose: () => {
        dialog.hide();
      }
    });
  }

  renderOperations = (value, index, record) => {
    return (
      <div>
        <span
          title="编辑"
          style={styles.operBtn}
          onClick={this.handleAddAndEdit.bind(this, record)}
        >
          <Icon size="xxs" type="edit" />
        </span>
        <span
          title="删除"
          style={styles.operBtn}
          onClick={this.handleDelete.bind(this, record)}
        >
          <Icon size="xxs" type="close" />
        </span>
      </div>
    )
  };

  /**
   * 得到每个组的组员
   * @return Object
   */
  async getTeamMember() {
    const res = await request.get('/teamMember/list');
    let { code, msg } = res.data;
    if(code !== 0) {  // code不为0
      throw new Error("getTeamMember返回code不为0");
    }
    let { teamMember } = msg;
    return teamMember;
  }

  /**
   * 得到当月的排班表数据
   * @param year
   * @param month
   * @return Object
   */
  async getScheduleList({ year, month }) {
    const res = await request.post('/workingSchedule/list', {
      year,
      month,
    });
    let { code, msg } = res.data;
    if( code !== 0 ) {
      throw new Error("getScheduleList返回code不为0");
    }
    let { scheduleList } = msg;
    return scheduleList;
  }

  /**
   * 添加或更新排班
   * @param id
   * @param teamName
   * @param scheduleTime
   * @param startTime
   * @param endTime
   * @param year
   * @param month
   * @param day
   * @param scheduleType
   * @return Object
   */
  async addOrUpdateSchedule({ id, teamName, scheduleTime, startTime, endTime, year, month, day, scheduleType }) {
    const res = await request
      .post(id ? '/leader/workingSchedule/update' : '/leader/workingSchedule/add', {
        id,
        teamName,
        scheduleTime,
        year,
        month,
        day,
        startTime: moment(startTime).unix() * 1000,
        endTime : moment(endTime).unix() * 1000,
        scheduleType,
      });
    let { code, msg } = res.data;
    if(code !== 0) {
      throw new Error("添加或更新排班接口code不为0");
    }
    let { newTableData, newList } = msg;
    return {
      newTableData,
      newList,
    };
  }

  /**
   * 删除排班
   * @param id
   * @return Integer
   */
  async deleteSchedule({ id }) {
    const res = await request
      .post('/leader/workingSchedule/delete', {
        id
      });
    let { code, msg } = res.data;
    if(code !== 0) {
      throw new Error("删除排班接口code不为0");
    }
    let { newList } = msg;
    return newList;
  }

  /**
   * 刷新组件函数
   * @return {Promise<void>}
   */
  async refreshComponent() {
    let teamMember = await this.getTeamMember();
    let scheduleList = await this.getScheduleList({ year: currentDate.year(), month: currentDate.month() });
    let day = this.state.currentDate.date();
    this.setState({
      teamMember,
      scheduleList,
      scheduleTableData: scheduleList[day - 1] || [],
      __loading: false,
    });
  }

  async getAndSetUserPrivilege() {
    let res = await request.get('/personalData');
    let { code, msg } = res.data;
    if( code !== 0 ) {
      throw new Error(`code为${code}`);
    }
    let { user } = msg;
    let showEditTable = user.browsePrivileges.workingScheduleEdit;
    this.setState({
      showEditTable,
    });
  }

  setExportButton() {
    let tableId = 'exportTable';
    let date = this.state.currentDate;
    TableExport(document.getElementById(tableId), {
      formats: ['xlsx'],
      trimWhitespace: false,
      exportButtons: true,
      filename: `${date.year()}年${date.month() + 1}月排班表`,
    });
  }

  /**
   * 导出
   */
  handleExport() {
    return request
      .post('/workingSchedule/export', {
        year: this.state.currentDate.year(),
        month: this.state.currentDate.month(),
      }).then((res) => {
        let {code, msg} = res.data;
        let { exportTableData } = msg;
        this.setState({
          exportTableData,
        }, () => {
          // todo: 好神奇啊，不用阿里的飞冰Table还不行，普通的Table导出根本没数据！
          this.setExportButton();
          document.getElementsByClassName('button-default xlsx')[0].click();
        });
      });
  }

  renderExportData(day, value, idx, row) {
    let { duty } = row;
    let type = '';
    duty.forEach((ele) => {
      if(ele.day === day) {
        type = ele.type;
      }
    });
    return type;
  }

  async componentDidMount() {
    await this.getAndSetUserPrivilege();
    await this.refreshComponent();
  }

  render() {
    return (
      <div>
        {
          this.state.__loading ||
          <Row className='working-schedule'>
            <Col span={
              24
              // this.state.showEditTable ? 18 : 24
            }>
              <IceContainer
                key='key'
                style={{ padding: '0', marginBottom: '0px' }}
                // style={this.state.showEditTable ? { paddingRight: '20px' } : { paddingRight: '40px' }}
              >
                <Row style={styles.titleContainer}>
                  <Col>
                    <div style={{ height: '60px', background: '#EAEBEF' }}>
                      <div style={
                        {
                          float: 'left',
                          fontSize: '20px',
                          fontWeight: 'bold',
                          height: '60px',
                          lineHeight: '60px',
                          paddingLeft: '30px',
                        }
                      }>
                        <FoundationSymbol type='activity' style={{ display: 'inline', verticalAlign: 'middle' }}/>
                        <span>&nbsp;排班表</span>
                      </div>
                      <div style={{
                        float: 'right',
                        lineHeight: '60px',
                        marginRight: '20px',
                      }}>
                        <Button
                          className='exportButton'
                          type='primary'
                          onClick={this.handleExport.bind(this)}
                        >导出到Excel</Button>
                      </div>
                    </div>
                  </Col>
                </Row>
                <Row>
                  <Col span={this.state.showEditTable ? 18 : 24}>
                    <div style={{ padding: '0 30px', marginTop: '10px' }}>
                      <Calendar
                        // showOtherMonth={false}
                        ref='calendar'
                        dateCellRender={this.dateCellRender.bind(this)}
                        monthCellRender={this.monthCellRender.bind(this)}
                        onVisibleMonthChange={this.onVisibleMonthChange.bind(this)}
                        onSelect={this.onCellSelect.bind(this)}
                      />
                    </div>
                  </Col>
                  {
                    this.state.showEditTable &&
                    <Col span={6}>
                      <div>
                        <IceContainer key='key' style={{ padding: '0 20px 0 0' }}>
                          {/*<Row>*/}
                          {/*<Col style={{ background: '#EAEBEF' }}>*/}
                          {/*<div className="panel-title">*/}
                          {/*<FoundationSymbol type='edit2' size='medium' style={{ display: 'inline', verticalAlign: 'middle' }}/>*/}
                          {/*<span>&nbsp;编辑排班</span>*/}
                          {/*</div>*/}
                          {/*</Col>*/}
                          {/*</Row>*/}
                          <Row>
                            <Col style={{ padding: '0 4px' }}>
                              <div style={{
                                fontSize: '15px',
                                fontWeight: 'bold',
                                float: 'left',
                                height: '40px',
                                lineHeight: '40px',
                              }}>
                                {this.state.currentDate.month() + 1}月{this.state.currentDate.date()}日排班详情
                              </div>
                              <div style={{
                                height: '40px',
                                lineHeight: '40px',
                                float: 'right',
                              }}>
                                <Button
                                  style={styles.addButton}
                                  text={true}
                                  type='default'
                                  onClick={this.handleAddAndEdit.bind(this, {})}
                                >
                                  <Icon size='xxs' type="add" className='addIcon'/>
                                </Button>
                              </div>
                              <div style={{ clear: 'both' }}/>
                            </Col>
                          </Row>
                          <Table
                            hasBorder={false}
                            dataSource={this.state.scheduleTableData}
                          >
                            <Table.Column
                              align='center'
                              style={styles.tableCell}
                              title="班组"
                              dataIndex="teamName"
                              width={80}
                            />
                            <Table.Column
                              align='center'
                              style={styles.tableCell}
                              title="倒班类型"
                              dataIndex="scheduleType"
                              width={140}
                            />
                            <Table.Column
                              align='center'
                              style={styles.tableCell}
                              title="值班时间"
                              width={350}
                              cell={(value, index, row) => {
                                let startTime = row.startTime;
                                let endTime = row.endTime;
                                return `${moment(startTime).format('H:mm')}-${moment(endTime).format('H:mm')}`
                              }}
                            />
                            <Table.Column
                              align='center'
                              style={styles.tableCell}
                              title="操作"
                              width={100}
                              cell={this.renderOperations}
                            />
                          </Table>
                        </IceContainer>
                      </div>
                    </Col>
                  }
                </Row>
                <Table
                  id="exportTable"
                  dataSource={this.state.exportTableData}
                  className="basic-table"
                  hasBorder={true}
                  primaryKey="key"
                  style={{ textAlign: 'center', visibility:'hidden', height: '1px', width:'100%' }}
                >
                  <Table.Column
                    title="姓名"
                    lock
                    width={200}
                    dataIndex="userName"
                  />
                  <Table.Column
                    title="所属班组"
                    dataIndex="teamName"
                  />
                  {
                    Array.from({ length: this.state.currentDate.daysInMonth() }).map((ele, index) => {
                      let day = index + 1;
                      let date = this.state.currentDate;
                      let weekDay = moment({ year: date.year(), month: date.month(), day: day }).day();  // 得到其是周几
                      weekDay = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'][weekDay];
                      return (
                        <Table.ColumnGroup
                          key={index}
                          title={`${day}号`}
                        >
                          <Table.Column
                            title={weekDay}
                            cell={this.renderExportData.bind(this, day)}
                          />
                        </Table.ColumnGroup>
                      )
                    })
                  }
                </Table>
              </IceContainer>
            </Col>
          </Row>
        }
      </div>
    )
  }

}

export default WorkingSchedule;

const styles = {
  titleContainer: {
  },
  calendarTitle: {
    fontSize: '18px',
    fontWeight: 'bold',
    height: '32px',
    lineHeight: '30px',
    margin: '10px 0 15px 4px',
    paddingLeft: '12px',
    borderLeft: '4px solid rgb(102, 102, 102)',
  },
  addButton: {
    border: '1px solid rgb(146, 146, 146)',
    borderRadius: '50%',
    color: 'rgb(146, 146, 146)',
    height: '16px',
    lineHeight: '12px',
    width: '16px',
  },
  operBtn: {
    display: 'inline-block',
    width: '14px',
    height: '16px',
    borderRadius: '999px',
    color: '#929292',
    background: '#f2f2f2',
    textAlign: 'center',
    cursor: 'pointer',
    lineHeight: '16px',
    marginRight: '2px',
  },
  tableCell: {
    fontSize: '12px',
  },
};
